package com.starsray.dynamic.datasource.listener;

import com.alibaba.fastjson.JSONObject;
import com.starsray.dynamic.ds.core.DatasourceOperator;
import com.starsray.dynamic.ds.params.DatasourceProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 消息接收器侦听器
 *
 * @author starsray
 * @since 2021-11-17
 */
@Component
@Slf4j
public class DsAddRedisListener implements MessageListener {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private DatasourceOperator datasourceOperator;


    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<String> redisSerializer = redisTemplate.getStringSerializer();
        String msg = redisSerializer.deserialize(message.getBody());
        DatasourceProperties properties = JSONObject.parseObject(msg, DatasourceProperties.class);
        Set<String> listDatasource = datasourceOperator.listDatasource();
        assert properties != null;
        if (!listDatasource.contains(properties.getUsername())) {
            datasourceOperator.addDatasource(properties);
            log.info("【多数据源】新增-重新加载，数据源信息：{}", properties.getUsername());
        }
    }

}